import { DD_SYSTEM } from '@/constants/api-pre';
import { request } from '@/service/request';

/** role */
export type Role = Api.Common.CommonRecord<{
  id: number;
  /** role name */
  name: string;
  /** role code */
  code: string;
  /** role description */
  remark: string;
  /** role status */
  sort: number;
  /** role type */
  type: string;
  /** role createTime */
  createTime: Date;
  /** role label */
  label: string;
  /** role value */
  value: string;
  /** role keywords */
  keywords: string;
}>;

/** role search params */
export type RoleSearchParams = CommonType.RecordNullable<
  Pick<Role, 'keywords' | 'status'> & Api.Common.CommonSearchParams
>;

export type RoleEditAndCreateParams = CommonType.RecordNullable<Pick<Role, 'name' | 'code' | 'status'>>;

/** role list */
export type RoleList = Api.Common.PaginatingQueryRecord<Role>;

/** all role */
export type AllRole = Pick<Role, 'name' | 'code' | 'id' | 'label' | 'value'>;

/** 获取角色表单 URL */
export function getFetchRoleUrl(id: number) {
  return `${DD_SYSTEM}/roles/${id}/form`;
}

/** get role list */
export function fetchGetRoleList(params?: RoleSearchParams) {
  return request<RoleList>({
    url: `${DD_SYSTEM}/roles/page`,
    method: 'get',
    params
  });
}

/**
 * get all roles
 *
 * these roles are all enabled
 */
export function fetchAllRolesOptions() {
  return request<AllRole[]>({
    url: `${DD_SYSTEM}/roles/options`,
    method: 'get'
  });
}

/**
 * 删除角色
 *
 * @param ids
 */
export function deleteRoles(ids: string) {
  return request<boolean>({
    url: `${DD_SYSTEM}/roles/${ids}`,
    method: 'delete'
  });
}

/**
 * 编辑角色
 *
 * @param id
 * @param data
 */
export function updateRole(id: number, data?: RoleEditAndCreateParams) {
  return request<boolean>({
    url: `${DD_SYSTEM}/roles/${id}`,
    method: 'put',
    data
  });
}

/**
 * 新增角色
 *
 * @param data
 */
export function createRole(data: RoleEditAndCreateParams) {
  return request<boolean>({
    url: `${DD_SYSTEM}/roles`,
    method: 'post',
    data
  });
}

/**
 * 获取角色的首页
 *
 * @param roleId
 */
export function fetchHomePageByRoleId(roleId: number) {
  return request<string>({
    url: `${DD_SYSTEM}/permission/role/${roleId}/home-page`,
    method: 'get'
  });
}

/**
 * 设置角色的首页
 *
 * @param roleId
 * @param homePage 路由名称
 */
export function updateHomePageByRoleId(roleId: number, homePage: string) {
  return request<string>({
    url: `${DD_SYSTEM}/permission/role/${roleId}/home-page`,
    method: 'put',
    data: { homePage }
  });
}

/**
 * 设置角色的菜单
 *
 * @param roleId
 * @param menuIds
 */
export function assignRoleMenu(roleId: number, menuIds: number[]) {
  return request<boolean>({
    url: `${DD_SYSTEM}/permission/role/${roleId}/menus`,
    method: 'post',
    data: menuIds
  });
}
